/********************************************************/
/*	Copyright (C) 2012 Gong Li Bin			*/
/*	Project:	MapReduce			*/
/*	Author:		gong_libin			*/
/*	Date:		2013_07_05			*/
/*	File:		MrHubTest.cpp			*/
/********************************************************/

#include "MrHub.h"

int main(int argc, char* argv[])
{
	CMrTcp CTcp;
	int iLength = 0;
	CMrPro CProSend;
	CMrPro CProRecv;
	char szKey[MR_PACKET] = { 0 };
	char szVal[MR_PACKET] = { 0 };
	UCHAR uszSend[MR_PACKET] = { 0 };
	UCHAR uszRecv[MR_PACKET] = { 0 };
	MRPROKV_S stRecv[MR_MR_VAL];
	MRPROKV_S stSend = {MR_MR_KEY, 0, (UCHAR*)szKey};
	MRPROHEAD_S stHead = {
		MR_PRO_FLAG,
		MR_PRO_1,
		MR_PRO_DATA,
		MR_PRO_0,
		MR_PRO_Y,
		MR_PRO_0,
		MR_DEF_EHUB,
		MR_DEF_SELT,
		MR_PRO_0,
		MR_DEF_SUCC,
		MR_MR_KEY,
		MR_PRO_0,
	};

	if (argc < 2) {
		MR_PRINT("Usage: %s key\n", argv[0]);
		return MR_SUCCESS;
	}

	strcpy(szKey, argv[1]);
	stSend.m_iLength = strlen(szKey);

	CProSend.MrProPutBody(NULL);
	CProSend.MrProInduce(&stHead);
	CProSend.MrProPutLength(MrProKvOutput(&stSend, MR_MR_KEY, &uszSend[MR_PRO_HEAD], MR_PACKET - MR_PRO_HEAD));
	CProSend.MrProCreate(uszSend, MR_PACKET);

	if (MR_SUCCESS == CTcp.MrTcpConnect((char*)"172.16.8.211", (char*)"12001")) {
		CTcp.MrTcpSetLinger(0);
		CTcp.MrTcpSetNoDelay();
		if (CTcp.MrNetSend(uszSend, MR_PRO_HEAD + CProSend.MrProGetLength()) > 0) {
			memset(uszRecv, '\0', MR_PACKET);
			if (MR_PRO_HEAD == CTcp.MrNetRecv(uszRecv, MR_PRO_HEAD)) {
				CProRecv.MrProReset();
				CProRecv.MrProParse(uszRecv, MR_PRO_HEAD);
				CProRecv.MrProDisplay();
				if (CProRecv.MrProGetLength() > 0) {
					iLength = CTcp.MrNetRecvAll(&uszRecv[MR_PRO_HEAD], CProRecv.MrProGetLength());
					if (iLength == CProRecv.MrProGetLength()) {
						memset(stRecv, '\0', sizeof(MRPROKV_S) * MR_MR_VAL);
						MrProKvInput(stRecv, MR_MR_VAL, &uszRecv[MR_PRO_HEAD], iLength);
						memcpy(szVal, stRecv[1].m_puszValue, stRecv[1].m_iLength);
						MR_PRINT("Key[%s] -> %s\n", szKey, szVal);
					}
					else {
						MR_ERROR("Failed to MrNetRecv\n");
					}
				}
				else {
					MR_PRINT("Key[%s] not found\n", szKey);
				}
			}
			else {
				MR_ERROR("Failed to MrNetRecv\n");
			}
		}
		else {
			MR_ERROR("Failed to MrNetSend\n");
		}
		CTcp.MrNetClose();
	}
	else {
		MR_ERROR("Failed to MrTcpConnect\n");
	}

	return MR_SUCCESS;
}
